﻿using OneDrive;
using System;
using System.Text;
using ZquenceStudio3Host.Storage.FileSystemStorage.BuiltInPlugins;

namespace Zquence_Studio_3.Shared
{
    public class OriginalWebClient : IWebClient
    {
        public event DownloadProgressChangedEventHandler DownloadProgressChanged;
        public event OpenReadCompletedEventHandler OpenReadCompleted;
            
        public void OpenReadAsync(Uri Address)
        {
            WrappedHttpClientRequest httpClient = new WrappedHttpClientRequest(Address);
            httpClient.Method = "GET";

            SharpDepend.Manager.ThreadManager.RunThread("HttpClientRequest", (Action)delegate
            {
                // Get responce.
                var handle1 = httpClient.GetResponseAsync();
                while (!handle1.IsCompleted)
                {
                    SharpDepend.Manager.ThreadManager.Sleep(100);
                }

                // Get content responce.
                var handle2 = handle1.Result.GetResponseStreamAsync();
                while (!handle2.IsCompleted)
                {
                    SharpDepend.Manager.ThreadManager.Sleep(100);
                }

                byte[] data = new byte[handle2.Result.Length];
                handle2.Result.Read(data, 0, data.Length);
                string htmlContent = UTF8Encoding.UTF8.GetString(data, 0, data.Length);
                    
                var call = OpenReadCompleted;
                if (call != null)
                {
                    call(this, new OpenReadCompletedEventArgs
                    {
                        ContentType = handle1.Result.ContentType,
                        Stream = handle2.Result,
                        ContentHeaders = handle1.Result.ContentHeaders
                    });
                }
            });
        }
    }
}
